from fastapi import APIRouter, Depends, HTTPException
from datetime import datetime

from schemas.content import (
    ContentGenerateRequest, ContentContinuationRequest, 
    ContentAdaptationRequest, ContentAssessmentRequest,
    ContentResponse, ContentGenerateResponse, 
    ContentContinuationResponse, ContentAdaptationResponse,
    ContentAssessmentResponse
)
from services.content_service import AIService

router = APIRouter(prefix="/content", tags=["content"])

# 依赖注入
def get_content_service():
    return AIService()

def clean_text(text: str) -> str:
    """清理文本中的多余转义字符"""
    # 处理常见的转义字符问题
    text = text.replace('\\n', '\n')
    text = text.replace('\\"', '"')
    text = text.replace('\\', '')  # 处理剩余的单个反斜杠
    # 移除可能的JSON字符串转义
    text = text.replace('\\"', '"')
    # 移除多余的引号和括号
    text = text.replace('");', '')
    text = text.replace('",', '')
    text = text.replace('\",', '')


    return text

@router.post("/generate", response_model=ContentResponse)
async def generate_content(
    request: ContentGenerateRequest,
    content_service: AIService = Depends(get_content_service)
):
    try:
        title, content, hashtag, totalToken = await content_service.generate_content(
            type_=request.type,
            platform=request.platform,
            description=request.description,
            reference_title=request.referenceTitle,
            reference_content=request.referenceContent
        )
        
        # 清理文本中的多余转义字符
        content = clean_text(content)
        if title:
            title = clean_text(title)
        
        return ContentResponse(
            code=200,
            message="文案生成成功",
            data=ContentGenerateResponse(
                title=title,
                content=content,
                hashtag=hashtag, 
                createdAt=datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
                totalToken=totalToken
            )
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"文案生成失败: {str(e)}")

# 续写接口
@router.post("/continuation", response_model=ContentResponse)
async def continuation_content(
    request: ContentContinuationRequest,
    content_service: AIService = Depends(get_content_service)
):
    try:
        content, totalToken = await content_service.continuation_content(
            original_content=request.originalContent,
            description=request.description,
            type_=request.type,
            platform=request.platform,
            reference_title=request.referenceTitle,
            reference_content=request.referenceContent
        )
        
        # 清理文本中的多余转义字符
        content = clean_text(content)
        
        return ContentResponse(
            code=200,
            message="续写文案生成成功",
            data=ContentContinuationResponse(
                content=content,
                createdAt=datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
                totalToken=totalToken
            )
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"文案续写失败: {str(e)}")

# 改写接口
@router.post("/adaptation", response_model=ContentResponse)
async def adaptation_content(
    request: ContentAdaptationRequest,
    content_service: AIService = Depends(get_content_service)
):
    try:
        content, totalToken = await content_service.adaptation_content(
            original_content=request.originalContent,
            content_to_be_adapted=request.contentToBeAdapted,
            description=request.description,
            type_=request.type,
            platform=request.platform,
            reference_title=request.referenceTitle,
            reference_content=request.referenceContent
        )
        
        return ContentResponse(
            code=200,
            message="文案改写成功",
            data=ContentAdaptationResponse(
                content=content,
                createdAt=datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
                totalToken=totalToken
            )
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"文案改写失败: {str(e)}")

@router.post("/assessment", response_model=ContentResponse)
async def assess_content(
    request: ContentAssessmentRequest,
    content_service: AIService = Depends(get_content_service)
):
    try:
        is_recommend, tags, recommend_reason = await content_service.assess_content(
            type_=request.type,
            platform=request.platform,
            content=request.content
        )
        
        return ContentResponse(
            code=200,
            message="文案标签和推荐理由生成成功",
            data=ContentAssessmentResponse(
                ifRecommend=is_recommend,
                tags=tags,
                recommendReason=recommend_reason
            )
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"文案评估失败: {str(e)}")